package ui;

import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.JTable;
import java.awt.Color;
import java.awt.Component;
import java.util.List;

/**
 * 自定义表格单元格渲染器，用于保持背景色不被选中或焦点状态影响
 */
public class ColorTableCellRenderer extends DefaultTableCellRenderer {
    private Color backgroundColor;

    public ColorTableCellRenderer() {
        this.backgroundColor = null;
    }

    /**
     * 设置背景色
     * @param color 背景色
     */
    public void setBackgroundColor(Color color) {
        this.backgroundColor = color;
    }
    
    /**
     * 获取背景色
     * @return 背景色
     */
    public Color getBackgroundColor() {
        return this.backgroundColor;
    }

    @Override
    public Component getTableCellRendererComponent(JTable table, Object value,
                                                   boolean isSelected, boolean hasFocus, int row, int column) {
        super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);

        // 如果有设置的背景色，则使用它，否则使用默认背景色
        if (backgroundColor != null) {
            setBackground(backgroundColor);
        } else {
            setBackground(table.getBackground());
        }
        setForeground(Color.BLACK);
        setOpaque(true);

        return this;
    }
    
    /**
     * 为指定列创建并设置单元格渲染器
     * @param table 表格
     * @param columnIndex 列索引
     * @param renderers 渲染器列表
     */
    public static void setColumnRenderer(JTable table, int columnIndex, List<ColorTableCellRenderer> renderers) {
        table.getColumnModel().getColumn(columnIndex).setCellRenderer(new DefaultTableCellRenderer() {
            @Override
            public Component getTableCellRendererComponent(JTable table, Object value,
                                                           boolean isSelected, boolean hasFocus, int row, int column) {
                if (row < renderers.size()) {
                    return renderers.get(row).getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
                }
                return super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
            }
        });
    }
}
